package com.rrs.client.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.rrs.client.R
import com.rrs.client.Utils
import com.rrs.client.databinding.ItemGoodsBinding
import com.rrs.client.detail.GoodsDetailActivity
import com.rrs.client.detail.PolicyDetailActivity
import com.rrs.client.entity.Goods
import kotlinx.coroutines.DelicateCoroutinesApi
import okhttp3.OkHttpClient
import java.text.SimpleDateFormat
import java.util.Locale


internal class GoodsAdapter(
    private val context: Context,
    private val list: List<Goods>,
) :
    RecyclerView.Adapter<GoodsAdapter.ViewHolder>() {
    val utils = Utils(context)
    val client = OkHttpClient()
    var formatter = SimpleDateFormat("yy/MM/dd HH:mm", Locale.CHINA)


    internal class ViewHolder(binding: ItemGoodsBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var main = binding.main
        var title = binding.title
        var price = binding.price

        //var date = binding.date
        var coverImg = binding.coverImg
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodsAdapter.ViewHolder {
        val binding = ItemGoodsBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: GoodsAdapter.ViewHolder, position: Int) {
        val item = list[position]
        holder.title.text = item.name
        holder.price.text = String.format(Locale.CHINA, "%.2f", item.priceCent!!.toDouble() / 100)
        //holder.date.text = formatter.format(Date(item.addTime!!.time))
        Glide.with(context)
            .load("${context.resources.getString(R.string.ServerUrl)}/getFile?name=${item.img}&path=goodsImg/")
            .into(holder.coverImg)
        holder.main.setOnClickListener {
            val intent = Intent()
            intent.setClass(context, GoodsDetailActivity::class.java)
            intent.putExtra("id", "${item.id}")
            context.startActivity(intent)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

}